const Service = require('egg').Service;
const _ = require('lodash');
const queue = require('async/queue');
const moment = require('moment');

/** @namespace ctx.service.processTypeData */
class AService extends Service {

  /**
   * @method start
   * 开始统计10秒之前所属的日期的所有anchorData的任务
   * @param today {String}
   * @returns {Promise<void>}
   */
  async start (today) {
    const status = await this.app.redis.get('note:spider_mission_status');
    if (status) {
      const _status = JSON.parse(status);
      _status['最后统计分类数据时间'] = moment().format('YYYY-MM-DD HH:mm:ss');
      this.app.redis.set('note:spider_mission_status', JSON.stringify(_status));
    }
    const redisKey = 'anchor_data:' + today;
    console.log('processTypeData 开始读取数据', moment().format('HH:mm:ss'));
    const [anchorDateData, active_minutes] = await Promise.all([
      this.app.redis.hgetall(redisKey),
      /*this.app.model.AnchorData.findAll(
        {
          raw: true,
          where: {created_at: today},
        }),*/
      this.app.redis.get('config:active_minutes'),
    ]);
    const activeMinute = parseInt(active_minutes);

    //缓存
    const typeData = {}, platformTypeAssociation = {}, platformTypeData = {};

    console.log('processTypeData 开始计算数据', moment().format('HH:mm:ss'));
    _.each(anchorDateData, anchorData => {
      anchorData = JSON.parse(anchorData);
      const key = anchorData.platform_id + '_' + anchorData.type_id;
      let data = typeData[key];
      if (!data) {
        data = typeData[key] = {
          platform_id: anchorData.platform_id,
          type_id: anchorData.type_id,
          num_active: 0,
          num_new: 0,
          num_open: 0,
          num_gift: 0,
          num_watch: 0,
          num_follower: 0,
        };

        //相同平台的归为一个数组
        if (!platformTypeData[data.platform_id])
          platformTypeData[data.platform_id] = [];
        platformTypeData[data.platform_id].push(data);
      }
      if (anchorData.num_live > activeMinute)
        data.num_active++;
      if (anchorData.is_new_anchor)
        data.num_new++;

      data.num_open++;
      data.num_gift += anchorData.num_gift;
      data.num_watch += anchorData.num_watch;
      data.num_follower += anchorData.num_follower;

      //绑定平台和直播类型
      if (!platformTypeAssociation[key])
        platformTypeAssociation[key] = {
          platform_id: anchorData.platform_id,
          type_id: anchorData.type_id,
        };

    });

    console.log('processTypeData 开始排序', moment().format('HH:mm:ss'));
    //相同平台的活跃主播数量为倒序的排序排名

    _.each(platformTypeData, list => {
      _.sortBy(list, 'num_active').
        reverse().
        forEach((item, rank) => {item.rank = rank + 1;});
    });

    console.log('processTypeData 开始保存数据', moment().format('HH:mm:ss'));
    const saveQueue = queue(async typeData => {
      const [data, isNew] = await this.app.model.TypeData.findOrCreate({
        where: {
          created_at: today,
          platform_id: typeData.platform_id,
          type_id: typeData.type_id,
        },
        defaults: typeData,
      });
      if (isNew)
        return;
      data.set(typeData);
      if (data.changed())
        await data.save();
    }, 20);

    _.each(typeData, data => {
      saveQueue.push(data);
    });
    await new Promise(resolve => {
      saveQueue.drain = () => {
        resolve();
      };
    });

    console.log('processTypeData 开始保存平台分类关系', moment().format('HH:mm:ss'));
    //保存平台和直播类型的关系
    const savePTQueue = queue(async data => {
      await this.app.model.PlatformType.findOrCreate(
        {where: data, defaults: data});
    }, 20);
    _.each(platformTypeAssociation, data => savePTQueue.push(data));

    await new Promise(resolve => {
      savePTQueue.drain = () => {
        resolve();
      };
    });

    console.log('processTypeData 任务结束', moment().format('HH:mm:ss'));
  }
}

module.exports = AService;